<template>
  <el-drawer
    v-model="renderVisible"
    :title="props.title"
    destroy-on-close
    :size="props.size"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <el-form
      ref="formRef"
      :label-position="'top'"
      label-width="100px"
      :model="formData"
      :rules="formRules"
    >
      <el-form-item label="上级菜单" prop="pid">
        <PipeSelectTree
          v-model="formData.pid"
          :options="tableData"
          :rootId="props.rowData.id"
        />
      </el-form-item>
      <el-form-item label="分类名称" prop="title">
        <el-input v-model="formData.title"></el-input>
      </el-form-item>
      <el-form-item label="封面图" prop="cover">
        <el-input v-model="formData.cover"></el-input>
      </el-form-item>
    </el-form>

    <template #footer>
      <PipeResetBtn :formEl="formRef">重置</PipeResetBtn>
      <el-button
        type="primary"
        @click="handleClickSubmit(formRef)"
        :loading="isLoading"
        >提交</el-button
      >
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { reactive, ref, watch, computed, PropType } from 'vue';
import type { ElForm } from 'element-plus';
import { ElMessage } from 'element-plus';
import { addGoodsCategory, updateGoodsCategory } from '@/apis/goods-category';
import { loopPropAssignment } from '@/utils/util';

import { useCategoryStore } from '@/stores/category';
const categoryStore = useCategoryStore();
const { getCategoryTree } = categoryStore;

// 加载状态
const isLoading = ref(false);

// 表单ref
const formRef = ref<InstanceType<typeof ElForm>>();

// 表单数据
const GetFormData = (): API.goodsCategory.EntityDto => ({
  pid: 0,
  title: '',
  cover: '',
  state: 1,
  coverList: []
});
const formData = reactive(GetFormData());

const formRules = reactive({
  pid: [{ required: true, trigger: 'change', message: '请选择上级菜单' }],
  title: [
    { type: 'string', required: true, message: '请输入权限' },
    { max: 32, trigger: 'blur', message: '长度不能超过32位字符' }
  ]
});

// tree数据
const tableData = getCategoryTree();

// props
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },

  title: String,

  size: {
    type: [String, Number],
    default: '30%'
  },

  isEdit: {
    type: Boolean,
    default: false
  },

  rowData: {
    // type: Object as PropType<TempsPost>,
    type: Object as PropType<API.goodsCategory.EntitySchema>,
    default: () => ({})
  }
});

// emits
const emits = defineEmits(['update:modelValue', 'onRefresh']);

// computed - 抽屉[显示|隐藏]
const renderVisible = computed({
  get: () => props.modelValue,
  set: (val) => {
    emits('update:modelValue', val);
  }
});

// watch
watch(
  () => props.modelValue,
  (val) => {
    if (!val) return;

    // 当rowData发生变化，初始化数据
    loopPropAssignment(formData, props.rowData);
  },
  {
    immediate: true
  }
);

// btn - submit
const handleClickSubmit = (formEl: InstanceType<typeof ElForm> | undefined) => {
  if (!formEl) return;
  formEl.validate(async (valid) => {
    if (!valid) return;
    if (props.isEdit) {
      submitDataUpdate(props.rowData.id!);
    } else {
      submitDataAdd();
    }
  });
};

// submit - add
const submitDataAdd = () => {
  isLoading.value = true;
  addGoodsCategory(formData)
    .then((res) => {
      isLoading.value = false;
      ElMessage.success(res.message);
      // 关闭弹窗
      emits('onRefresh');
      renderVisible.value = false;
    })
    .catch(() => {
      isLoading.value = false;
    });
};

// submit - update
const submitDataUpdate = (id: number) => {
  isLoading.value = true;
  updateGoodsCategory(id, formData)
    .then((res) => {
      isLoading.value = false;
      ElMessage.success(res.message);
      // 关闭弹窗
      emits('onRefresh');
      renderVisible.value = false;
    })
    .catch(() => {
      isLoading.value = false;
    });
};
</script>

<style lang="scss" scoped></style>
